package com.canaan.business.service.inOutStock.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import com.canaan.business.common.enums.inOutStock.*;
import com.canaan.business.common.enums.storehouse.InOutStorageOperationEnum;
import com.canaan.business.common.enums.storehouse.StockOccupyStatusEnum;
import com.canaan.business.common.enums.storehouse.StoreHouseTypeEnum;
import com.canaan.business.common.enums.storehouse.StorehouseStockStatusEnum;
import com.canaan.business.domain.basic.WmsStorehouse;
import com.canaan.business.domain.inOutStock.*;
import com.canaan.business.domain.storehouse.StockCheck;
import com.canaan.business.domain.storehouse.WmsInOutStorage;
import com.canaan.business.domain.storehouse.WmsStorehouseStock;
import com.canaan.business.mapper.inOutStock.WmsStockOccupyMapper;
import com.canaan.business.service.basic.IWmsProductService;
import com.canaan.business.service.basic.IWmsStorehouseLocationService;
import com.canaan.business.service.basic.IWmsStorehouseService;
import com.canaan.business.service.inOutStock.IStockOccupyDetailService;
import com.canaan.business.service.inOutStock.IStorehouseStockCheckService;
import com.canaan.business.service.inOutStock.IWmsStockOccupyService;
import com.canaan.business.service.storehouse.IWmsInOutStorageService;
import com.canaan.business.service.storehouse.IWmsStorehouseStockService;
import com.canaan.common.exception.ServiceException;
import com.canaan.common.utils.DateUtils;
import com.canaan.common.utils.SecurityUtils;
import com.canaan.common.utils.StringUtils;
import com.canaan.common.utils.TableNoUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 库存占用Service业务层处理
 *
 * @author ruoyi
 * @date 2023-02-07
 */
@Service
public class WmsStockOccupyServiceImpl implements IWmsStockOccupyService {
    @Resource
    private WmsStockOccupyMapper stockOccupyMapper;
    @Resource
    private IWmsStorehouseStockService wmsStorehouseStockService;
    @Resource
    private IStockOccupyDetailService stockOccupyDetailService;
    @Resource
    private IWmsInOutStorageService wmsInOutStorageService;
    @Resource
    private IWmsStorehouseLocationService wmsStorehouseLocationService;
    @Resource
    private IWmsStorehouseService wmsStorehouseService;
    @Resource
    private IWmsProductService wmsProductService;
    @Resource
    private IStorehouseStockCheckService storehouseStockCheckService;

    /**
     * 查询库存占用
     *
     * @param id 库存占用主键
     * @return 库存占用
     */
    @Override
    public WmsStockOccupy selectWmsStockOccupyById(Long id) {
        return stockOccupyMapper.selectWmsStockOccupyById(id);
    }

    /**
     * 查询库存占用列表
     *
     * @param stockOccupy 库存占用
     * @return 库存占用
     */
    @Override
    public List<WmsStockOccupy> selectWmsStockOccupyList(WmsStockOccupy stockOccupy) {
        return stockOccupyMapper.selectWmsStockOccupyList(stockOccupy);
    }

    /**
     * 新增库存占用
     *
     * @param stockOccupy 库存占用
     * @return 结果
     */
    @Override
    public int insertWmsStockOccupy(WmsStockOccupy stockOccupy) {
        if(StringUtils.isBlank(stockOccupy.getNo())){
            stockOccupy.setNo(TableNoUtil.getNo(WmsStockOccupy.class));
        }
        stockOccupy.setCreateBy(SecurityUtils.getUsername());
        stockOccupy.setCreateTime(DateUtils.getNowDate());
        return stockOccupyMapper.insertWmsStockOccupy(stockOccupy);
    }

    /**
     * 批量新增库存占用
     *
     * @param stockOccupyList 库存占用列表
     * @return 结果
     */
    @Override
    public int batchInsertWmsStockOccupy(List<WmsStockOccupy> stockOccupyList) {
        String username = SecurityUtils.getUsername();
        Date currerTime = DateUtils.getNowDate();
        for (WmsStockOccupy stockOccupy : stockOccupyList){
            if(StringUtils.isBlank(stockOccupy.getNo())){
                stockOccupy.setNo(TableNoUtil.getNo(WmsStockOccupy.class));
            }
            stockOccupy.setCreateBy(username);
            stockOccupy.setCreateTime(currerTime);
        }
        int insertNum = 0;
        for (int i=0; i<stockOccupyList.size();) {
            int endIndex = i+500;
            if (endIndex > stockOccupyList.size()) {
                endIndex = stockOccupyList.size();
            }
            insertNum = insertNum + stockOccupyMapper.batchInsertWmsStockOccupy(stockOccupyList.subList(i, endIndex));
            i = endIndex;
        }
        return insertNum;
    }

    /**
     * 修改库存占用
     *
     * @param stockOccupy 库存占用
     * @return 结果
     */
    @Override
    public int updateWmsStockOccupy(WmsStockOccupy stockOccupy) {
        stockOccupy.setUpdateBy(SecurityUtils.getUsername());
        stockOccupy.setUpdateTime(DateUtils.getNowDate());
        return stockOccupyMapper.updateWmsStockOccupy(stockOccupy);
    }

    /**
     * 批量修改库存占用
     *
     * @param stockOccupyList 库存占用列表
     * @return 结果
     */
    @Override
    public int batchUpdateWmsStockOccupy(List<WmsStockOccupy> stockOccupyList) {
        String username = SecurityUtils.getUsername();
        Date currerTime = DateUtils.getNowDate();
        for (WmsStockOccupy stockOccupy : stockOccupyList){
            stockOccupy.setUpdateBy(username);
            stockOccupy.setUpdateTime(currerTime);
        }
        int updateNum = 0;
        for (int i=0; i<stockOccupyList.size();) {
            int endIndex = i+500;
            if (endIndex > stockOccupyList.size()) {
                endIndex = stockOccupyList.size();
            }
            updateNum = updateNum + stockOccupyMapper.batchUpdateWmsStockOccupy(stockOccupyList.subList(i, endIndex));
            i = endIndex;
        }
        return updateNum;
    }

    /**
     * 批量删除库存占用
     *
     * @param ids 需要删除的库存占用主键集合
     * @return 结果
     */
    @Override
    public int deleteWmsStockOccupyByIds(Long[] ids) {
        WmsStockOccupy stockOccupy = new WmsStockOccupy();
        stockOccupy.setIds(Arrays.asList(ids));
        List<WmsStockOccupy> stockOccupyList = stockOccupyMapper.selectWmsStockOccupyList(stockOccupy);
        for (WmsStockOccupy occupy : stockOccupyList){
            occupy.setStatus(com.canaan.business.common.enums.inOutStock.StockOccupyStatusEnum.INVALID.getCode());
        }
        return stockOccupyMapper.batchUpdateWmsStockOccupy(stockOccupyList);
    }

    /**
     * 删除库存占用信息
     *
     * @param id 库存占用主键
     * @return 结果
     */
    @Override
    public int deleteWmsStockOccupyById(Long id) {
        return stockOccupyMapper.deleteWmsStockOccupyById(id);
    }

    /**
     * 查询库存占用
     *
     * @param no 编号
     * @return 库存占用
     */
    @Override
    public WmsStockOccupy selectWmsStockOccupyByNo(String no) {
        return stockOccupyMapper.selectWmsStockOccupyByNo(no);
    }

    /**
     * 批量删除库存占用
     *
     * @param nos 需要删除的编号集合
     * @return 结果
     */
    @Override
    public int deleteWmsStockOccupyByNos(String[] nos) {
        return stockOccupyMapper.deleteWmsStockOccupyByNos(nos);
    }

    /**
     * 删除库存占用信息
     *
     * @param no 编号
     * @return 结果
     */
    @Override
    public int deleteWmsStockOccupyByNo(String no) {
        return stockOccupyMapper.deleteWmsStockOccupyByNo(no);
    }

    /**
     * 占用取消
     *
     * @param taskNo 任务编号
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int stockOccupyCancel(String taskNo) {
        //取关联的库存占用
        if(StringUtils.isEmpty(taskNo)){
            return 0;
        }
        WmsStockOccupy entity = new WmsStockOccupy();
        entity.setTaskNo(taskNo);
        entity.setType(StockOccupyTypeEnum.OCCUPY.getCode());
        List<WmsStockOccupy> list = this.selectWmsStockOccupyList(entity);
        if(list.isEmpty()){
            entity.setType(StockOccupyTypeEnum.WAIT_INSPECTION_FREEZE.getCode());
            list = this.selectWmsStockOccupyList(entity);
        }
        if(list.isEmpty()){
            throw new ServiceException("占用编号不存在");
        }
        entity = list.get(0);
        StockOccupyDetail detail = new StockOccupyDetail();
        detail.setStockOccupyNo(entity.getNo());
        List<StockOccupyDetail> detailList = stockOccupyDetailService.selectStockOccupyDetailList(detail);
        if(!detailList.isEmpty()) {
            //清空占用明细
            Long[] ids = detailList.stream().map(StockOccupyDetail::getId).toArray(Long[]::new);
            stockOccupyDetailService.deleteStockOccupyDetailByIds(ids);
        }
        return this.deleteWmsStockOccupyById(entity.getId());
    }

    /**
     * 库存占用处理
     * @param taskNo          任务编号
     * @param storehouseNo    仓库
     * @param productNo       物料编号
     * @param occupyQty       占用数量
     * @param workNo          工单编号
     * @param areaNo          库区编号
     * @return  结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean stockOccupy(String taskNo, String storehouseNo, String productNo, Long occupyQty,String workNo,String areaNo,String whetherMp){

        if(StringUtils.isEmpty(taskNo) || StringUtils.isEmpty(storehouseNo)
                || StringUtils.isEmpty(productNo) || occupyQty == null){
            throw new ServiceException("库存占用处理缺少必要参数");
        }else if(occupyQty < 1 ){
            return true;
        }
        List<StockOccupyDetail> occupyDetailList = new ArrayList<>();

        WmsStorehouse storehouse = wmsStorehouseService.selectWmsStorehouseByNo(storehouseNo);
        if(storehouse == null){
            throw new ServiceException("仓库不存在");
        }

        synchronized (storehouseNo + ":" + productNo) {
            //取出可用库存信息
            Long stockQty = 0L;
            List<Object> stocks = null;
            if(StoreHouseTypeEnum.DJC.getCode().equals(storehouse.getTypeNo())) {
                //待检仓库存查询
                StorehouseStockCheck stockCheck = new StorehouseStockCheck();
                stockCheck.setStorehouseNo(storehouseNo);
                stockCheck.setProductNo(productNo);
                if (StringUtils.isNotEmpty(areaNo)){
                    stockCheck.setStorehouseAreaNo(areaNo);
                }
                List<StorehouseStockCheck> stockCheckList = storehouseStockCheckService.selectStorehouseStockCheckList(stockCheck);
                stockQty = stockCheckList.stream().mapToLong(StorehouseStockCheck::getQty).sum();
                stocks = stockCheckList.stream().sorted(Comparator.comparing(StorehouseStockCheck::getId)).collect(Collectors.toList());
            }else {
                //普通库存查询
                List<WmsStorehouseStock> stockList = this.wmsStorehouseStockService.getStock(storehouseNo,productNo,null,areaNo,whetherMp,workNo);
                stockQty = stockList.stream().filter(e->(e.getStatus().equals(StorehouseStockStatusEnum.NORMAL.getCode()))||e.getStatus().equals(StorehouseStockStatusEnum.POOR.getCode())).mapToLong(WmsStorehouseStock::getQty).sum();
                stocks = stockList.stream().sorted(Comparator.comparing(WmsStorehouseStock::getId)).collect(Collectors.toList());
            }
            //取出已有的占用明细信息
            StockOccupyDetail detailParams = new StockOccupyDetail();
            detailParams.setStorehouseNo(storehouseNo);
            detailParams.setProductNo(productNo);
            List<StockOccupyDetail> detailList = stockOccupyDetailService.selectStockOccupyDetailList(detailParams);
            Long oldOccupyQty = detailList.stream().mapToLong(StockOccupyDetail::getOccupyQty).sum();

            if (occupyQty > stockQty - oldOccupyQty) {
                throw new ServiceException("库存可用数不足");
            }
//            Map<String,Long> oldOccupyQtyMap = detailList.stream()
//                    .collect(Collectors.toMap(StockOccupyDetail::getStorehouseLocationNo,StockOccupyDetail::getOccupyQty));
            Map<String,Long> oldOccupyQtyMap =detailList.stream().collect(Collectors.groupingBy(StockOccupyDetail::getStorehouseLocationNo,Collectors.summingLong(StockOccupyDetail::getOccupyQty)));
            //初始化占用信息
            WmsStockOccupy entity = new WmsStockOccupy();
            entity.setTaskNo(taskNo);
            entity.setStatus(com.canaan.business.common.enums.inOutStock.StockOccupyStatusEnum.VALID.getCode());
            String type = StoreHouseTypeEnum.DJC.getCode().equals(storehouse.getTypeNo())
                    ? StockOccupyTypeEnum.WAIT_INSPECTION_FREEZE.getCode() : StockOccupyTypeEnum.OCCUPY.getCode();
            entity.setType(type);
            this.insertWmsStockOccupy(entity);
            //处理库存数据和记录占用明细

            for (Object o : stocks) {
                String storehouseLocationNo = "";
                Long qty = 0L;
                if(o instanceof StorehouseStockCheck){
                    StorehouseStockCheck check = (StorehouseStockCheck)o;
                    storehouseLocationNo = check.getStorehouseLocationNo();
                    qty = check.getQty();
                }else if(o instanceof WmsStorehouseStock){
                    WmsStorehouseStock stock = (WmsStorehouseStock)o;
                    storehouseLocationNo = stock.getStorehouseLocationNo();
                    qty = stock.getQty();
                }

                //判断是否已经被占用完了
                oldOccupyQty = oldOccupyQtyMap.getOrDefault(storehouseLocationNo,0L);
                if(qty - oldOccupyQty < 0){
                    continue;
                }
                //占用明细初始化
                StockOccupyDetail occupyDetail = new StockOccupyDetail();
                occupyDetail.setStockOccupyNo(entity.getNo());
                occupyDetail.setProductNo(productNo);
                occupyDetail.setStorehouseLocationNo(storehouseLocationNo);
                occupyDetail.setStorehouseNo(storehouseNo);
                if (StringUtils.isNotEmpty(workNo)){
                    occupyDetail.setWorkNo(workNo);
                }
                //设置库存占用的数量和库存的数量加减
                if (occupyQty >= qty) {
                    //剩余的占用数大于或等于库存数量
                    occupyDetail.setOccupyQty(qty);
                    occupyQty = occupyQty - qty;
                } else {
                    //剩余的占用数小于库存数量
                    occupyDetail.setOccupyQty(occupyQty);
                    occupyQty = 0L;
                }
                if(occupyDetail.getOccupyQty() > 0L) {
                    //有效数据再进行保存处理
                    occupyDetailList.add(occupyDetail);
                }
                if (occupyQty <= 0) {
                    break;
                }
            }
            //保存占用信息
            if(!occupyDetailList.isEmpty()) {
                stockOccupyDetailService.batchInsertStockOccupyDetail(occupyDetailList);
            }
        }
        return true;
    }

    /**
     * 占用解除
     * @param taskOrder 拣货单
     * @param records   拣货记录
     * @param businessNo 业务单号，出入库单号
     * @return
     */
    @Override
    public int stockOccupyUnlock(PickerTaskOrder taskOrder, List<WmsPickingRecord> records,String businessNo){
        if(taskOrder == null || StringUtils.isEmpty(taskOrder.getNo()) || CollectionUtils.isEmpty(records)){
            return 0;
        }

        WmsStockOccupy occupy = new WmsStockOccupy();
        occupy.setTaskNo(taskOrder.getNo());
        occupy.setType(StockOccupyTypeEnum.OCCUPY.getCode());
        List<WmsStockOccupy> occupyList = stockOccupyMapper.selectWmsStockOccupyList(occupy);
        if(occupyList.isEmpty()){
            //普通仓库没有的就转去查询待检仓占用，如果再多加就先判断仓库
            occupy.setType(StockOccupyTypeEnum.WAIT_INSPECTION_FREEZE.getCode());
            occupyList = stockOccupyMapper.selectWmsStockOccupyList(occupy);
        }
        if(occupyList.isEmpty()){
            throw new ServiceException("缺少占用信息");
        }
        //库存列表
        List<Object> stocks = null;
        List<Object> stockBarcodes = null;

        List<String> barcodes = records.stream().map(WmsPickingRecord::getBarcode).collect(Collectors.toList());
        if(StockOccupyTypeEnum.WAIT_INSPECTION_FREEZE.getCode().equals(occupyList.get(0).getType())){
            List<StorehouseStockCheck> checkList = storehouseStockCheckService.getListByBarcodes(barcodes);
            stockBarcodes = checkList.stream().map(StorehouseStockCheck::getBarcode).collect(Collectors.toList());
            stocks = new ArrayList<>(checkList);
        }else {
            List<WmsStorehouseStock> stockList = wmsStorehouseStockService.getListByBarcodes(barcodes);
            stockBarcodes = stockList.stream().map(WmsStorehouseStock::getBarcode).collect(Collectors.toList());
            stocks = new ArrayList<>(stockList);
        }
        //校验库存信息
        List<String> notSpecifyBarcodeList = new ArrayList<>();
        List<String> nonentityBarcodeList = new ArrayList<>();
        List<String> abnormalBarcodeList = new ArrayList<>();
        Map<String,Object> stockMap = new HashMap<>();
        for (Object stock : stocks) {
            String storehouseNo = "";
            String productNo = "";
            String barcode = "";
            String status = "";
            if(stock instanceof StorehouseStockCheck){
                //待检仓库存
                StorehouseStockCheck check = (StorehouseStockCheck)stock;
                storehouseNo = check.getStorehouseNo();
                productNo = check.getProductNo();
                barcode = check.getBarcode();
                status = check.getStatus();
            }else if(stock instanceof WmsStorehouseStock){
                //普通库存
                WmsStorehouseStock storehouseStock = (WmsStorehouseStock)stock;
                storehouseNo = storehouseStock.getStorehouseNo();
                productNo = storehouseStock.getProductNo();
                barcode = storehouseStock.getBarcode();
                status = storehouseStock.getStatus();
            }
            if(!taskOrder.getStorehouseNo().equals(storehouseNo)
                    || !taskOrder.getProductNo().equals(productNo)){
                //不是指定的仓库或物料
                notSpecifyBarcodeList.add(barcode);
            }else if(!stockBarcodes.contains(barcode)){
                //不存在
                nonentityBarcodeList.add(barcode);
            }else if(stock instanceof WmsStorehouseStock && (StorehouseStockStatusEnum.LOCK.getCode().equals(status)||StorehouseStockStatusEnum.FREEZE.getCode().equals(status))){
                //普通库存需要校验该条码的库存状态是否异常
                abnormalBarcodeList.add(barcode);
            }
            stockMap.put(barcode, stock);
        }
        if(!notSpecifyBarcodeList.isEmpty()){
            throw new ServiceException(notSpecifyBarcodeList + "条码不是指定的仓库或物料");
        }else if(!nonentityBarcodeList.isEmpty()){
            throw new ServiceException(nonentityBarcodeList + "条码不存在");
        }else if(!abnormalBarcodeList.isEmpty()){
            throw new ServiceException(abnormalBarcodeList + "条码库存状态异常");
        }
        //明细列表
         StockOccupyDetail detail = new StockOccupyDetail();
        detail.setStockOccupyNo(occupyList.get(0).getNo());
        List<StockOccupyDetail> occupyDetailList = stockOccupyDetailService.selectStockOccupyDetailList(detail);
        Map<String, List<StockOccupyDetail>> orderDetailMap = occupyDetailList.stream()
                .collect(Collectors.groupingBy(StockOccupyDetail::getStorehouseLocationNo));

        //扣减对应库存的占用数
        List<StockOccupyDetail> updateDetailList = new ArrayList<>();
        for (WmsPickingRecord record : records) {
            Object stock = stockMap.get(record.getBarcode());
            if(stock == null){
                throw new ServiceException(record.getBarcode() + "条码的库存不足或不存在");
            }
            //修改占用明细
           List<StockOccupyDetail> detailList = orderDetailMap.get(record.getStorehouseLocationNo());
            if (CollectionUtil.isNotEmpty(detailList)){
                for (StockOccupyDetail item:detailList){
                    item.setOccupyQty(item.getOccupyQty() - record.getPickingQty());
                    if (item.getOccupyQty() < 1) {
                        item.setDelFlag("1");
                    }
                    updateDetailList.add(item);
                }
            }
            //初始化出入库记录
            WmsInOutStorage storage = new WmsInOutStorage();
            if(stock instanceof StorehouseStockCheck){
                //待检仓库存
                StorehouseStockCheck check = (StorehouseStockCheck)stock;
                storage.setProductNo(check.getProductNo());
                storage.setProductName(check.getProductName());
                storage.setProductUnit(check.getCompany());
                storage.setBarcode(check.getBarcode());
                storage.setBatchNo(check.getBatchNo());
                storage.setStorehouseNo(check.getStorehouseNo());
                storage.setAreaNo(check.getStorehouseAreaNo());
                storage.setStorehouseLocationNo(check.getStorehouseLocationNo());
            }else if(stock instanceof WmsStorehouseStock){
                //普通库存
                WmsStorehouseStock storehouseStock = (WmsStorehouseStock)stock;
                storage.setProductNo(storehouseStock.getProductNo());
                storage.setProductName(storehouseStock.getProductName());
                storage.setProductUnit(storehouseStock.getCompany());
                storage.setBarcode(storehouseStock.getBarcode());
                storage.setBatchNo(storehouseStock.getBatchNo());
                storage.setStorehouseNo(storehouseStock.getStorehouseNo());
                storage.setAreaNo(storehouseStock.getStorehouseAreaNo());
                storage.setStorehouseLocationNo(storehouseStock.getStorehouseLocationNo());
            }
            storage.setQuantity(record.getPickingQty());
            storage.setRelNo(taskOrder.getRelOrderNo());
            if (StringUtils.isNotEmpty(businessNo)){
                storage.setBusinessNo(businessNo);
            }
            storage.setType(this.inoutTypeConvert(taskOrder.getType()));
            storage.setOperation(InOutStorageOperationEnum.OUT.getCode());
            wmsInOutStorageService.insertWmsInOutStorage(storage);
        }

        if(!updateDetailList.isEmpty()){
            if(OutOrderStatusEnum.ACCOMPLISH.getCode().equals(taskOrder.getStatus())){
                occupyDetailList.forEach((item) -> { item.setDelFlag("1"); });
                stockOccupyDetailService.batchUpdateStockOccupyDetail(occupyDetailList);
                occupyList.get(0).setStatus(com.canaan.business.common.enums.inOutStock.StockOccupyStatusEnum.INVALID.getCode());
                stockOccupyMapper.updateWmsStockOccupy(occupyList.get(0));
            }else{
                stockOccupyDetailService.batchUpdateStockOccupyDetail(updateDetailList);
                //如果占用明细为空时把占用主表改为失效
                detail = new StockOccupyDetail();
                detail.setStockOccupyNo(occupyList.get(0).getNo());
                occupyDetailList = stockOccupyDetailService.selectStockOccupyDetailList(detail);
                if(occupyDetailList.isEmpty()){
                    occupyList.get(0).setStatus(com.canaan.business.common.enums.inOutStock.StockOccupyStatusEnum.INVALID.getCode());
                    stockOccupyMapper.updateWmsStockOccupy(occupyList.get(0));
                }
            }
        }
        return 1;
    }

    @Override
    public void createLock(StockCheck stockCheck, List<WmsStorehouseStock> wmsStorehouseStocks) {
        WmsStockOccupy stockOccupy = new WmsStockOccupy();
        stockOccupy.setTaskNo(stockCheck.getNo());
        stockOccupy.setType(StockOccupyTypeEnum.LOCK.getCode());
        stockOccupy.setStatus(com.canaan.business.common.enums.inOutStock.StockOccupyStatusEnum.VALID.getCode());
        this.insertWmsStockOccupy(stockOccupy);
        List<StockOccupyDetail> occupyDetails = new ArrayList<>();
        for (WmsStorehouseStock wmsStorehouseStock : wmsStorehouseStocks) {
            StockOccupyDetail occupyDetail = new StockOccupyDetail();
            occupyDetail.setStockOccupyNo(stockOccupy.getNo());
            occupyDetail.setStorehouseLocationNo(wmsStorehouseStock.getStorehouseLocationNo());
            occupyDetail.setBarcode(wmsStorehouseStock.getBarcode());
            occupyDetail.setProductNo(wmsStorehouseStock.getProductNo());
            occupyDetails.add(occupyDetail);
        }
        stockOccupyDetailService.batchInsertStockOccupyDetail(occupyDetails);
    }

    @Override
    public void unLock(StockCheck stockCheck) {
        WmsStockOccupy stockOccupy = selectByTaskNo(stockCheck.getNo(), StockOccupyTypeEnum.LOCK.getCode());
        if (stockOccupy != null) {
            stockOccupy.setStatus(com.canaan.business.common.enums.inOutStock.StockOccupyStatusEnum.INVALID.getCode());
            this.updateWmsStockOccupy(stockOccupy);
            StockOccupyDetail occupyDetail = new StockOccupyDetail();
            occupyDetail.setStockOccupyNo(stockOccupy.getNo());
            List<StockOccupyDetail> occupyDetails = stockOccupyDetailService.selectStockOccupyDetailList(occupyDetail);
            List<Long> ids = occupyDetails.stream().map(StockOccupyDetail::getId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(ids)){
                stockOccupyDetailService.deleteStockOccupyDetailByIds(ArrayUtil.toArray(ids,Long.class));
            }
            List<String> barcodes = occupyDetails.stream().map(e -> e.getBarcode()).collect(Collectors.toList());
            List<WmsStorehouseStock> listByBarcodes = this.wmsStorehouseStockService.getListByBarcodes(barcodes);
            listByBarcodes.stream().forEach(e->e.setStatus(StorehouseStockStatusEnum.NORMAL.getCode()));
            wmsStorehouseStockService.batchUpdateWmsStorehouseStock(listByBarcodes);
        }
    }

    public WmsStockOccupy selectByTaskNo(String taskNo,String type){
        WmsStockOccupy stockOccupy = new WmsStockOccupy();
        stockOccupy.setTaskNo(taskNo);
        stockOccupy.setType(type);
        stockOccupy.setStatus(StockOccupyStatusEnum.EFFECT.getCode());
        List<WmsStockOccupy> wmsStockOccupies = this.selectWmsStockOccupyList(stockOccupy);
        if (CollUtil.isNotEmpty(wmsStockOccupies)){
            return wmsStockOccupies.get(0);
        }
        return null;
    }

    //出入库记录类型转换
    public Long inoutTypeConvert(Integer type){
        if(OutStockOrderTypeEnum.SALES.getCode().equals(type)){
            return InOutStockTypeEnum.SALES_OUT.getCode().longValue();
        }else if(OutStockOrderTypeEnum.PICK.getCode().equals(type)){
            return InOutStockTypeEnum.PICK_OUT.getCode().longValue();
        }else if(OutStockOrderTypeEnum.ADJUST.getCode().equals(type)){
            return InOutStockTypeEnum.ADJUST_OUT.getCode().longValue();
        }else if(OutStockOrderTypeEnum.RETURN.getCode().equals(type)){
            return InOutStockTypeEnum.RETURN_OUT.getCode().longValue();
        }else  if(OutStockOrderTypeEnum.MP.getCode().equals(type)){
            return InOutStockTypeEnum.MP_IN.getCode().longValue();
        }
        else {
            return InOutStockTypeEnum.OTHER_OUT.getCode().longValue();
        }
    }
}
